package com.sample.springbatch.job.splitfile;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.batch.item.file.FlatFileFooterCallback;
import org.springframework.batch.item.file.FlatFileHeaderCallback;
import org.springframework.batch.item.file.FlatFileItemWriter;
import org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor;
import org.springframework.batch.item.file.transform.DelimitedLineAggregator;
import org.springframework.core.io.PathResource;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Writer;
import java.util.Date;

/**
 * Flat文件格式写入类  实现了分隔符格式
 * @author zwg
 */
public class RepayOrderInfoZoneWriter<RepayOrderInfoZone> extends FlatFileItemWriter {

    public RepayOrderInfoZoneWriter(String zone) {
        setResource(new PathResource("target/data/repay-orders_zone_"+zone+".dat"));
        setAppendAllowed(false);

        setLineAggregator(new DelimitedLineAggregator<RepayOrderInfoZone>(){{
            setDelimiter("|");
            setFieldExtractor(new BeanWrapperFieldExtractor<RepayOrderInfoZone>(){{
                setNames(new String[] { "userId", "productId","contractNo","amount","repayType","repayMethod" });
            }});
        }});

        /**
         * 写文件头
         */
        setHeaderCallback(new FlatFileHeaderCallback() {
            @Override
            public void writeHeader(Writer writer) throws IOException {
                writer.write("#begin time: "+ DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
            }
        });

        /**
         * 写文件尾
         */
        setFooterCallback(new FlatFileFooterCallback() {
            @Override
            public void writeFooter(Writer writer) throws IOException {
                writer.write("#end time: "+ DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
            }
        });
    }

}
